import React, { useState, useEffect } from 'react';
import qs from 'qs';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, message, Spin } from 'antd';
import moment from 'moment';
import _ from 'lodash';
import ExtraComponent from '../components/ExtraComponent';
import ScreenDom from '../components/ScreenDom';
import { BaseTable, utils } from '@/components/BaseTable';
import * as api from '@/services/ReportMgr';
import { titleTree, fixedColumns } from './utils/data';

const IndexPage = () => {
  const [loading, setLoading] = useState(false);
  const [tip, setTip] = useState('数据加载中，请耐心等待......');
  const [dataSource, setDataSource] = useState([]);
  const [publicParams, setPublicParams] = useState({
    yearMonth: moment().format('YYYY-MM'),
    versionStatus: '',
    time: [],
    name: '',
  });

  // get request table data
  const reuqestData = async (params = publicParams) => {
    setLoading(true);
    setDataSource([]);
    setTip('数据加载中，请耐心等待......');
    const res = await api.signPlanProgressUsingGET({
      params: {
        yearMonth: params.yearMonth,
        versionStatus: params.versionStatus,
        name: params.name,
        startTime: _.isEmpty(params.time)
          ? ''
          : moment(params.time[0]).format('YYYY-MM-DD HH:mm:ss'), // 起始时间
        endTime: _.isEmpty(params.time) ? '' : moment(params.time[1]).format('YYYY-MM-DD HH:mm:ss'), // 开始时间
      },
    });
    if (res?.code === 1) {
      setDataSource(
        res.data.map((item, idx) => ({
          id: idx,
          ...item,
        })),
      );
    }

    setLoading(false);
  };

  // this is click exprot button
  const clickHandlerExport = callback => {
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ yearMonth: publicParams.yearMonth, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/report/signPlanProgressExport?${exportQueryString}`);
    setTimeout(() => {
      callback();
    }, 1000);
  };

  // click Refresh
  const clickHandlerRefresh = async () => {
    setLoading(true);
    setTip('数据刷新中，请耐心等待...');
    const res = await api.refreshSignPlanProgressUsingGET({
      params: {
        yearMonth: publicParams.yearMonth,
      },
    });
    if (res?.code === 1) {
      message.success(res.data, 1, reuqestData);
    } else {
      setLoading(false);
    }
  };

  const onChangeParams = (key, value) => {
    const params = { ...publicParams, [key]: value || '' };
    setPublicParams(params);
    reuqestData(params);
  };

  useEffect(() => {
    (() => reuqestData())();
  }, []);

  return (
    <PageHeaderWrapper
      className="page-header"
      breadcrumb={null}
      title={false}
      extra={
        <ExtraComponent
          params={publicParams}
          exportBtnAuthorized="SignPlan_Export"
          clickHandlerExport={clickHandlerExport}
          onChangeParams={onChangeParams}
        />
      }
    >
      <Card className="page-header-card" bordered={false}>
        <Spin spinning={loading} tip={tip}>
          <ScreenDom
            onChangeParams={onChangeParams}
            exportBtnAuthorized="SignPlan_Update"
            clickHandlerRefresh={clickHandlerRefresh}
          />
          <BaseTable
            subtractHeight="165px"
            headerHeight={[30]}
            fixedColumns={fixedColumns}
            headerRenderer={utils.getHeaderRenderer(titleTree, 1)}
            treeData={dataSource}
          />
        </Spin>
      </Card>
    </PageHeaderWrapper>
  );
};

export default IndexPage;
